package com.leoncom.sms_silencer;

import java.util.Calendar;

import com.leoncom.sms_silencer.util.CommonUtils;
import com.leoncom.sms_silencer.util.MuterHelper;
import com.leoncom.sms_silencer.util.SilencerTask;
import com.leoncom.sms_silencer.util.TaskDataSource;
import com.leoncom.sms_silencer.util.TaskScheduler;
import com.leoncom.sms_sliencer.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

public class SilencerActivity extends Activity {

	private TaskDataSource taskds;
	private SilencerTask currTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_silencer);
		this.initClickableField();
		this.taskds = new TaskDataSource(this);
		this.taskds.open();
		this.currTask = new SilencerTask();
		this.initHourSpinner();
		this.initMinuteSpinner();
		this.setEnable();
	}

	public void setEnable() {
		currTask = this.taskds.getTask();
		Button startButton = (Button) this.findViewById(R.id.button1);
		Button stopButton = (Button) this.findViewById(R.id.button2);
		TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker1);
		Spinner hourSpinner = (Spinner) this.findViewById(R.id.hour_spinner);
		Spinner minSpinner = (Spinner) this.findViewById(R.id.min_spinner);
		TextView daysView = (TextView) this
				.findViewById(R.id.repeatedDayContent);
		if (currTask != null) {
			timePicker.setCurrentHour(currTask.getHour());
			timePicker.setCurrentMinute(currTask.getMin());
			hourSpinner.setSelection(currTask.getPeriod() / 60);
			minSpinner.setSelection(currTask.getPeriod() % 60);
			timePicker.setEnabled(false);
			startButton.setEnabled(false);
			stopButton.setEnabled(true);
			hourSpinner.setEnabled(false);
			minSpinner.setEnabled(false);
			daysView.setText(currTask.concatPlainDayString(getApplicationContext()));
			daysView.setEnabled(false);
			this.initCurrentState();
		} else {
			timePicker.setEnabled(true);
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
			hourSpinner.setEnabled(true);
			minSpinner.setEnabled(true);
			daysView.setText(getResources().getString(R.string.RepeatedDayContent));
			daysView.setEnabled(true);
			this.currTask = new SilencerTask();
			this.initCurrentState();
		}
	}
	
	private void initCurrentState() {
		if(this.currTask == null) {
			return;
		}
		
		TextView currStateView = (TextView) this.findViewById(R.id.currentStates);
		String currStateText = "(Error)";
		if(this.currTask.isMuteNow()) {
			currStateText = this.getResources().getString(R.string.currentMuteStates);
		} else {
			currStateText = this.getResources().getString(R.string.currentUnMuteStates);
		}
		
		currStateView.setText(currStateText);
	}

	public void initHourSpinner() {
		Spinner hourSpinner = (Spinner) this.findViewById(R.id.hour_spinner);
		this.addNumbericSpinner(hourSpinner, 24);
	}

	public void initMinuteSpinner() {
		Spinner minSpinner = (Spinner) this.findViewById(R.id.min_spinner);
		this.addNumbericSpinner(minSpinner, 60);
	}

	public void addNumbericSpinner(Spinner spinner, int numUpperBound) {
		String[] items = new String[numUpperBound];
		for (int i = 0; i < numUpperBound; i++) {
			items[i] = String.valueOf(i);
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, items);
		spinner.setAdapter(adapter);
	}

	public int getSlientMinutes() {
		Spinner hourSpinner = (Spinner) findViewById(R.id.hour_spinner);
		Spinner minSpinner = (Spinner) findViewById(R.id.min_spinner);
		int hour = Integer.parseInt((String) hourSpinner.getSelectedItem());
		int min = Integer.parseInt((String) minSpinner.getSelectedItem());
		return hour * 60 + min;
	}

	public void initClickableField() {
		this.setTurnOnClick();
		this.setTurnOffClick();
		this.setSelectRepeatedField();
	}

	// insert task to sqlite, start service
	public void setTurnOnClick() {
		Button button = (Button) this.findViewById(R.id.button1);

		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// insert new scheduler task
				TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker1);
				currTask.setHour(timePicker.getCurrentHour());
				currTask.setMin(timePicker.getCurrentMinute());
				currTask.setPeriod(getSlientMinutes());
				currTask.setInit(true);
				taskds.createTask(currTask);
				TaskScheduler.scheduleAlarm(getApplicationContext(), currTask);
				setEnable();
			}
		});
	}

	// delete task from sqlite, stop service
	public void setTurnOffClick() {
		Button button = (Button) this.findViewById(R.id.button2);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				TaskScheduler.destroyAlarm(getApplicationContext(), currTask);
				taskds.deleteTask();
				MuterHelper.setToUnMute(getApplicationContext());
				setEnable();
			}
		});
	}

	public void setSelectRepeatedField() {
		LinearLayout repeatedField = (LinearLayout) this
				.findViewById(R.id.RepeatedField);
		repeatedField.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
					showRepeatedCheckBox();
			}
		});
	}

	public void showRepeatedCheckBox() {
		if(this.currTask.isInit() == true) {
			return;
		}
		
		final CharSequence[] weekDayItems = CommonUtils.getDayOfWeekNames(getApplicationContext(), Calendar.LONG);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getText(R.string.RepeatedDay));
		builder.setMultiChoiceItems(weekDayItems,
				this.currTask.getRepeatedDays(),
				new DialogInterface.OnMultiChoiceClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int indexSelected, boolean isChecked) {
						if (isChecked) {
							currTask.setRepeatedDay(indexSelected);
						} else {
							currTask.unsetRepeatedDay(indexSelected);
						}
					}
				})
				.setPositiveButton(getResources().getString(R.string.Confirm), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						TextView daysView = (TextView) findViewById(R.id.repeatedDayContent);
						daysView.setText(currTask.concatPlainDayString(getApplicationContext()));
					}
				})
				.setNegativeButton(getResources().getString(R.string.Cancel), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						// do nothing here
					}
				});
		builder.create().show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.sliencer, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
		    case R.id.about_app:
		    	this.showAppDialog();
		        return true;
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}
	
	private void showAppDialog() {
		// custom dialog
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.custom_dialog);
		dialog.setTitle(this.getResources().getString(R.string.app_name));

		// set the custom dialog components - text, image and button
		TextView text = (TextView) dialog.findViewById(R.id.text);
		text.setText(this.getResources().getString(R.string.copyright));
		ImageView image = (ImageView) dialog.findViewById(R.id.image);
		image.setImageResource(R.drawable.ic_launcher);

		Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}
}
